package com.tj.seed.admin.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tj.seed.admin.domain.entity.User;
import com.tj.seed.admin.domain.rep.LoginRep;
import com.tj.seed.admin.domain.req.LoginReq;
import com.tj.seed.common.context.UserContextHolder;
import com.tj.seed.common.domain.Result;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class LoginService {

    @Resource
    private UserService userService;

    /**
     * 登录实现
     *
     * @param req
     * @return
     */
    public Result<LoginRep> login(LoginReq req) {
        User user = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getLoginAccount, req.getLoginName()));
        if (user == null) {
            return Result.fail("登录名或者密码错误");
        }
        Pbkdf2PasswordEncoder passwordEncoder = new Pbkdf2PasswordEncoder(user.getSalt());
        passwordEncoder.setAlgorithm(Pbkdf2PasswordEncoder.SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA512);
        if (!passwordEncoder.matches(req.getPassword(), user.getPwd())) {
            return Result.fail("登录名或者密码错误");
        }
        return Result.success(LoginRep.builder().userId(user.getId()).loginName(user.getLoginAccount()).userName(user.getNickName()));
    }
}
